import React, {memo, useEffect, useRef, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {message, Popconfirm, Modal} from "antd";

import "./channel.css";
import Header from "../../../components/main-header/Header";
import {deepClone, getScanChannel} from "../../../common/utils";
import {saveChannelLists, saveChannelPosition, saveIsLoad} from "./store/actionCreators";
import {saveScanChannel} from "../../main/protocol/store/actionCreators";
import {saveData} from "../../main/store/actionCreators";

export default memo(function Channel() {
  const [channelLists, setChannelLists] = useState([
    [{name: "FAM", isSelected: true}, {name: "SYBR", isSelected: true}/*, {name: "EvaGreen", isSelected: true}*/],
    [{name: "VIC", isSelected: true}, {name: "HEX", isSelected: true}, {name: "JOE", isSelected: true}/*, {name: "540", isSelected: true}, {name: "560", isSelected: true}*/],
    [{name: "TAMRA", isSelected: true}, {name: "CY3", isSelected: true}],
    [{name: "ROX", isSelected: true}, {name: "TEX615", isSelected: true}, {name: "TEXAS RED", isSelected: true}/*, {name: "610", isSelected: true}*/],
    [{name: "CY5", isSelected: true}/*, {name: "LIZ", isSelected: true}, {name: "Mustang Purple", isSelected: true}, {name: "Quasar 670", isSelected: true}*/],
    [{name: "CY5.5", isSelected: true}, {name: "Quasar 705", isSelected: true}]]);
  const [channelInputs, setChannelInputs] = useState(new Array(6).fill(""));
  const [infoUp, setInfoUp] = useState(['475nm', '527nm', '537nm', '572nm', '623nm', '655nm']);
  const [info, setInfo] = useState(['524nm', '565nm', '583nm', '623nm', '676nm', '711nm']);
  const [downIndex, setDownIndex]  = useState(0);
  const [upIndex, setUpIndex]  = useState(0);
  const headerLists = ["Channel 1", "Channel 2", "Channel 3", "Channel 4", "Channel 5", "Channel 6"];
  const [isModalOpen, setIsModalOpen] = useState(false);
  const dispatch = useDispatch();
  const {data, isCN, isSave,userInfo} = useSelector(state => ({
    data: state.dataReducer.data,
    isCN: state.languageReducer.isCN,
    isSave: state.channelReducer.isSave,
    userInfo: state.loginReducer.info
  }));
  const passwordId = useRef();
  const waveInfo = useRef();
  let cloneChannelLists = []; //  克隆channel列表
  let cloneChannelInputs = [];
  let clearTime = [
    {time: 0, clear: false},
    {time: 0, clear: false},
    {time: 0, clear: false},
    {time: 0, clear: false},
    {time: 0, clear: false},
    {time: 0, clear: false}]; //  清除channel计数器

  useEffect(getChannel, []);  //  初始化localStorage中的信息

  const showModal = () => {
    // setDownIndex()
    setIsModalOpen(true);
  };
  const handleOk = () => {
    console.log();
    console.log(userInfo);
    if(passwordId.current.value !== userInfo.password){
      message.error('密码不正确')
    }else {
     let object = [...info];
      object[downIndex]=waveInfo.current.value;
     setInfo(object)
      message.success('修改成功')
    }
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //  获取localStorage中的channel
  function getChannel() {
    for (let i = 0; i < channelLists.length; i++) {
      cloneChannelLists.push(JSON.parse(localStorage.getItem(`channel${i}`)));
    }
    cloneChannelLists[0] && setChannelLists(cloneChannelLists);
  }

  //  保存channel到localStorage
  function saveChannel() {
    for (let i = 0; i < channelLists.length; i++) {
      localStorage.setItem(`channel${i}`, JSON.stringify(channelLists[i]));
    }
    let scanChannel = getScanChannel();
    let data_channels = [];
    scanChannel.forEach(it => {
      it.lists.forEach((item, index) => {
        //把channel里List为空的的删除干净
        !item.name && it.lists.splice(index, 1);
        //删除起始位置，删除长度
      });
      if (it.lists.every(item => !item.isSelected)) {
        it.scan = false;
        it.forbidden = true;
      }
    });
    data_channels = scanChannel.map(item => item.scan ? 1 : 0);
    // localStorage.setItem("selectedChannel", JSON.stringify(data_channels));
    dispatch(saveScanChannel([
      {...scanChannel[0], lists: channelLists[0]},
      {...scanChannel[1], lists: channelLists[1]},
      {...scanChannel[2], lists: channelLists[2]},
      {...scanChannel[3], lists: channelLists[3]},
      {...scanChannel[4], lists: channelLists[4]},
      {...scanChannel[5], lists: channelLists[5]}
    ]));
    dispatch(saveChannelLists(channelLists)); //  把channel放到redux中管理
    let channelPos = channelLists.map(channelList => channelList.map(channel => channel.name));
    dispatch(saveChannelPosition(channelPos));
    dispatch(saveData({...data, protocol: {...data.protocol, channels: data_channels}}));
    message.info("Save success");
  }

  //  输入新的channel
  function inputChannel(e, indey) {
    cloneChannelInputs = deepClone(channelInputs, cloneChannelInputs);
    cloneChannelInputs[indey] = e.target.value;
    setChannelInputs(cloneChannelInputs);
  }

  //  点击添加新channel
  function clickAddChannel(indey) {
    cloneChannelLists = deepClone(channelLists, cloneChannelLists);
    cloneChannelInputs = deepClone(channelInputs, cloneChannelInputs);
    cloneChannelLists[indey].push({name: channelInputs[indey], isSelected: true});
    cloneChannelInputs[indey] = "";
    setChannelLists(cloneChannelLists);
    setChannelInputs(cloneChannelInputs);
  }

  //  删除channel
  function deleteChannel(index, indey) {
    if (index === 0 && indey < 3) {
      return message.error("Unable to remove the default dye");
    } else if (index === 1 && indey < 5) {
      return message.error("Unable to remove the default dye");
    } else if (index === 2 && indey < 2) {
      return message.error("Unable to remove the default dye");
    } else if (index === 3 && indey < 3) {
      return message.error("Unable to remove the default dye");
    } else if (index === 4 && indey < 4) {
      return message.error("Unable to remove the default dye");
    } else if (index === 5 && indey < 2) {
      return message.error("Unable to remove the default dye");
    }
    cloneChannelLists = deepClone(channelLists, cloneChannelLists);
    cloneChannelLists[index].splice(indey, 1);
    setChannelLists(cloneChannelLists);
  }

  //  关闭channel
  function closeChannel(index, indey) {
    cloneChannelLists = deepClone(channelLists, cloneChannelLists);
    cloneChannelLists[index][indey].isSelected = !cloneChannelLists[index][indey].isSelected;
    setChannelLists(cloneChannelLists);
  }

  //  点击2次清空channel
  function clearChannelLists(indey) {
    if (clearTime[indey].time === 1) {
      cloneChannelLists = deepClone(channelLists, cloneChannelLists);
      clearTime[indey].time = 0;
      cloneChannelLists[indey].forEach((item, index) => item.isSelected = false);
      setChannelLists(cloneChannelLists);
    } else {
      clearTime[indey].time++;
    }
    if (!clearTime[indey].clear) {
      clearTime[indey].clear = true;
      setTimeout(() => {
        clearTime[indey].time = 0;
        clearTime[indey].clear = false;
      }, 1000); //  1秒内连点2次有效
    }
  }

  return (
    <div>
      <Header name={isCN ? "通道分配" : "Channel Assignment"} imgPosition="100px" isSave={true} saveAction={saveChannel} iconStyle="headerImg"/>
      <section className="mainSection settingChannel">
        <div className="settingChannelPart0">
          <div>Emission</div>
          <div/>
          <div>Excitation</div>
        </div>
        <div className="settingChannelPart1">
          <header>
            {
              headerLists.map((item, index) => (
                <div key={item} onClick={() => clearChannelLists(index)}>{item}</div>
              ))
            }
          </header>
          <div className="settingChannelContent">
            <header>
              {
                infoUp.map((it,index) => {
                  return <Popconfirm
                    title={isCN ? `是否要修改波长信息` : `Whether to modify the wavelength information?`}
                    onConfirm={()=>{
                      setUpIndex(index)
                      setIsModalOpen(true);
                    }}
                    okText="Yes"
                    cancelText="No"
                  >
                    <div>{it}</div>
                  </Popconfirm>;
                })
              }
           {/*   <div>475nm</div>
              <div>527nm</div>
              <div>537nm</div>
              <div>572nm</div>
              <div>623nm</div>
              <div>655nm</div>*/}
            </header>
            <div>
              {
                channelLists.map((item, index) => (
                  <section key={index}>
                    <div>
                      <div>
                        {
                          item.map((item, indey) => (
                            <div className={item.isSelected ? " " : "channelSleep"}
                                 onClick={() => closeChannel(index, indey)}
                                 onDoubleClick={() => deleteChannel(index, indey)}
                                 key={item.name}
                            >{item.name}</div>
                          ))
                        }
                        <input type="text"
                               value={channelInputs[index]}
                               onChange={e => inputChannel(e, index)}
                        />
                      </div>
                    </div>
                    <div style={{cursor: "pointer"}}
                         onClick={() => clickAddChannel(index)}
                    >Customer Dye
                    </div>
                  </section>
                ))
              }
            </div>
            <footer>
              {
                info.map((it,index) => {
                  return <Popconfirm
                    title={isCN ? `是否要修改波长信息` : `Whether to modify the wavelength information?`}
                    onConfirm={()=>{
                      setDownIndex(index)
                      setIsModalOpen(true);
                    }}
                    okText="Yes"
                    cancelText="No"
                  >
                    <div>{it}</div>
                  </Popconfirm>;
                })
              }
            </footer>
            {
              isModalOpen
                ?
                <Modal title="" visible={true} onOk={handleOk} onCancel={handleCancel} style={{width:300,height:300}} >
                  <div className="model">
                    <div>
                      <label>{isCN?'波段信息':'Information'}</label>
                      <input type="text" ref={waveInfo} defaultValue={info[downIndex]}/>
                    </div>
                    <div >
                      <label>{isCN?'密码':'Password'}</label>
                      <input ref={passwordId} type="password"/>
                    </div>
                  </div>

                </Modal> : null
            }
          </div>
        </div>
      </section>
    </div>
  );
});
